package main.controller;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.Date;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import main.entity.UserVO;
import main.service.IOService;
import main.service.UserService;
import main.utils.UtilPackage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value="/user")
public class UserCtrl extends BaseCtrl<UserVO> {

	@Autowired
	private UserService userService;
	@Autowired
	private IOService ioService;
	
	@RequestMapping(value="/toLogin.do", method=RequestMethod.GET)
	public String toLogin(){
		return "login";
	}
	
	@RequestMapping(value="/toRegister.do", method=RequestMethod.GET)
	public String toRegister(Model model){
		model.addAttribute("mode", "register");
		return "register_modify";
	}
	
	@RequestMapping(value="/toModify.do", method=RequestMethod.GET)
	public String toModify(Model model){
		model.addAttribute("mode", "modify");
		return "register_modify";
	}
	
	@RequestMapping(value="/toModifyHdImg.do", method=RequestMethod.GET)
	public String toModifyHdImg(Model model){
//		model.addAttribute("mode", "modify");
		return "headImg";
	}
	
	@RequestMapping(value="/modifyHdImg.do", method=RequestMethod.POST)
	public String modifyHdImg(@RequestParam("myFile") MultipartFile upFile, @RequestParam("UID")Integer UID, HttpServletRequest request, Model model){
		Boolean isOK = ioService.upHdImg(upFile, UID, request);
		return isOK ? "redirect: /"+UID+"/myzone.do" : "redirect: toModify.do";
	}
	
	@RequestMapping(value="/register.do", method=RequestMethod.POST)
	public ModelAndView register(@ModelAttribute UserVO userVO, ModelAndView mdv){
		Integer PK = userService.save(userVO);
		if (PK!=null) {
			mdv.setViewName("/"+PK+"/myzone.do");
		} else {
			mdv.addObject("mode", "register");
			mdv.setViewName("register_modify");
		}
		return mdv;
	}
	
	
    @InitBinder    
    protected void initBinder(WebDataBinder binder) {    
//        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));    
// /        binder.registerCustomEditor(int.class, new CustomNumberEditor(int.class, true));    
//        binder.registerCustomEditor(int.class, new IntegerEditor());    
// /        binder.registerCustomEditor(long.class, new CustomNumberEditor(long.class, true));  
//        binder.registerCustomEditor(long.class, new LongEditor());    
//        binder.registerCustomEditor(double.class, new DoubleEditor());    
//        binder.registerCustomEditor(float.class, new FloatEditor());
    	binder.registerCustomEditor(Date.class, new UtilPackage.MyDateEditor());
    }
	
/*	@RequestMapping(value="register.do", method=RequestMethod.POST)	
	@ResponseBody
	public Map<String, Object> register(@ModelAttribute UserVO userVO, BindingResult bindingResult){
		Map<String, Object> resMap = new HashMap<String, Object>();
		if (bindingResult.hasErrors()) {
			resMap.put("errorCode", "40001");
			resMap.put("errorMsg", bindingResult.getFieldError().getDefaultMessage());
		}
		resMap.put("user", userVO);
		return resMap;
	}*/
	
	@RequestMapping(value="/modify.do", method=RequestMethod.POST)
	public ModelAndView modify(@ModelAttribute UserVO userVO, ModelAndView mdv){
		Boolean isDone = userService.update(userVO);
		Integer uID = userVO.getUserID();
		if (isDone) {
			mdv.setViewName("/"+uID+"/myzone.do");
		} else {
			mdv.addObject("mode", "modify");
			mdv.setViewName("register_modify");
		}
		return mdv;
	}
	
	@RequestMapping(value="/login.do")
	public String login(@ModelAttribute UserVO userVO, @RequestParam String valicode, HttpServletRequest request) {
		String targetURL = "login";
		String realCode = (String) request.getSession().getAttribute("valicode");
		if(realCode.equals(valicode) && userService.hasUser(userVO)){
			request.getSession().setAttribute("unm", userVO.getUsername());
			targetURL = "redirect: /index.do";
		}
		return targetURL;
	}
	
	@RequestMapping("/logout.do")
	public String logout(@RequestParam String unm, HttpServletRequest request){
		String targetURL = "error";
		if (request.getSession().getAttribute("unm").equals(unm)) {
			targetURL = "login";
		}
		return targetURL;
	}
	
	@RequestMapping("/{uID}/myzone.do")
//	@ResponseBody
	public ModelAndView userCenter(@PathVariable("uID") Integer uID){
		Map<String, Object> infos = userService.userCenter(uID);
//		request.setAttribute("infos", infos);
		ModelAndView mdv = new ModelAndView();
		mdv.setViewName("my_zone");
		mdv.addObject("infos",infos);
//		String targetURL = "my_zone";
//		return targetURL;
		return mdv;
	}
	
	@RequestMapping("/valicode.do")
	public void getValiCode(HttpServletRequest request, HttpServletResponse response){
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/png");
		
		Integer height=25,width=50;
		BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB);
		Graphics graphics = image.getGraphics();
		Random rdm = new Random();
		graphics.setColor(UtilPackage.getRandomColor());
		graphics.fillRect(0, 0, height, width);
		graphics.setFont(new Font("Times New Roman", Font.PLAIN, 18));
		graphics.setColor(UtilPackage.getRandomColor());
		for (int i = 0; i < 50; i++) {
			Integer x = rdm.nextInt(width);
			Integer y = rdm.nextInt(height);
			Integer m = rdm.nextInt(15);
			Integer n = rdm.nextInt(15);
			graphics.drawLine(x, y, x+m, x+n);
		}
		StringBuffer strCodes = new StringBuffer();
		for (int j = 0; j < 4; j++) {			
			String code = String.valueOf(rdm.nextInt(10));
			strCodes.append(code);
			graphics.setColor(UtilPackage.getRandomColor());
			graphics.drawString(code, j*13, 16);
		}
		request.getSession().setAttribute("valicode", strCodes);
//		System.err.println("codes: "+request.getSession().getAttribute("codes"));
		try {
			ImageIO.write(image, "PNG", response.getOutputStream());
			response.getOutputStream().flush();
			response.getOutputStream().close();
			graphics.dispose();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
